package com.xh.baselibrary.utils.net.ping;

import android.os.SystemClock;

import com.xh.baselibrary.log.XLog;
import com.xh.baselibrary.utils.CloseableUtils;
import com.xh.baselibrary.utils.net.PingWorker;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

public class SocketConnectPolicy implements IPingPolicy{
    private String TAG = SocketConnectPolicy.class.getSimpleName();
    private volatile Socket mSocket;

    @Override
    public long ping(String host, int port) throws Exception {
        long ret = -1;
        mSocket = new Socket();
        try {
            long start = SystemClock.elapsedRealtime();
            XLog.i(TAG,"call start");
            mSocket.setSoTimeout(PingWorker.CONNECT_TIMEOUT);
            mSocket.connect(new InetSocketAddress(host,port));
            long end = SystemClock.elapsedRealtime();
            long usetime = end - start;
            XLog.i(TAG,"call() called end = "+usetime);
            ret = mSocket.isConnected() && usetime!= PingWorker.CONNECT_TIMEOUT_RESULT?usetime:PingWorker.CONNECT_TIMEOUT_RESULT;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            CloseableUtils.close(mSocket);
            mSocket = null;
        }
        return ret;
    }

    @Override
    public void close() {
    XLog.i(TAG,"socket close = "+(mSocket!=null));
    Socket socket = mSocket;
        if (socket != null) {
            try {
                mSocket.close();
                mSocket = null;
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
